package com.itheima.reggie.web;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.pojo.Category_分类;
import com.itheima.reggie.pojo.Dish_菜品;
import com.itheima.reggie.pojo.SetmealDish_套餐与菜品;
import com.itheima.reggie.pojo.Setmeal_套餐;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: cl
 * @Date: 2022/4/4 - 04 - 04
 * @Description:
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加套餐并且更新套餐菜品关系表
     *
     * @param setmealDto
     * @return
     */
    //@CacheEvict(value = "setmealCache",allEntries = true) //清除setmealCache名称下，所有的缓存数据
    @CacheEvict(value = "setmealCache", key = "#setmealDto.categoryId+'_1'")//定向清理
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        setmealService.saveWithDish(setmealDto);
        return R.success("套餐添加成功！");
    }

    /**
     * 分页展示套餐信息  包含套餐分类名称需要增强实体类处理
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        //分页构造器对象
        Page<Setmeal_套餐> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        setmealService.page(pageInfo,
                Wrappers.<Setmeal_套餐>lambdaQuery()
                        //添加查询条件，根据name进行like模糊查询
                        .like(name != null, Setmeal_套餐::getName, name)
                        //添加排序条件，根据更新时间降序排列
                        .orderByDesc(Setmeal_套餐::getUpdateTime)
        );


        //将对象拷贝补充处理
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<Setmeal_套餐> records = pageInfo.getRecords();

        //获取到套餐对象进行处理
        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item, setmealDto);
            //分类id  获取到id 查询出来category分类对象，获取分类对象名字并给setmealDto
            Long categoryId = item.getCategoryId();
            Category_分类 category = categoryService.getById(categoryId);

            if (category != null) {
                setmealDto.setCategoryName(category.getName());
            }
            return setmealDto;

        }).collect(Collectors.toList());
        dtoPage.setRecords(list);

        return R.success(dtoPage);

    }

    /**
     * 根据id查询套餐和套餐的菜品
     *
     * @param id
     * @return
     */

    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable long id) {
        SetmealDto setmealDto = setmealService.getByIdWithFlavor(id);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐信息和对应菜品
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache", allEntries = true) //清除setmealCache名称下，所有的缓存数据
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        setmealService.updateWithDish(setmealDto);
        return R.success("菜品信息修改成功！");
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true) //清除setmealCache名称下，所有的缓存数据
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids:{}", ids);
        setmealService.removeWithDish(ids);
        return R.success("套餐数据删除成功");
    }

    /**
     * 批量修改停售或在售
     *
     * @param status
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache", allEntries = true) //清除setmealCache名称下，所有的缓存数据
    @PostMapping("/status/{status}")
    public R<String> update(@PathVariable int status, Long[] ids) {

        Setmeal_套餐 setmeal = new Setmeal_套餐();
        setmeal.setStatus(status);
        setmealService.update(setmeal,
                Wrappers.<Setmeal_套餐>lambdaUpdate()
                        .in(Setmeal_套餐::getId, ids)
        );
        return R.success("修改在售状态成功！");
    }


    /**
     * 套餐基本信息展示
     *
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status", unless = "#result.data.size()==0")
    public R<List<Setmeal_套餐>> list(Setmeal_套餐 setmeal) {

        //通过套餐中得Category_分类id查询对应的套餐系列
        List<Setmeal_套餐> list = setmealService.list(
                Wrappers.<Setmeal_套餐>lambdaQuery()
                        //条件一：在售状态
                        .eq(Setmeal_套餐::getStatus, 1)
                        //条件二：接受得分类id存在且相等
                        .eq(setmeal.getCategoryId() != null, Setmeal_套餐::getCategoryId, setmeal.getCategoryId())
                        //排序
                        .orderByDesc(Setmeal_套餐::getUpdateTime)
        );
        return R.success(list);
    }

    @Autowired
    private DishService dishService;

    /**
     * 查看某个套餐中的详细信息
     *
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<Setmeal_套餐> setmeal(@PathVariable Long id) {

        //1、查询此套餐
        Setmeal_套餐 setmeal = setmealService.getById(id);

        //2、查询此套餐的所有菜品详情
        List<SetmealDish_套餐与菜品> list = setmealDishService.list(
                Wrappers.<SetmealDish_套餐与菜品>lambdaQuery()
                        .eq(SetmealDish_套餐与菜品::getSetmealId, id)
        );

        //3、查询菜品图片并复制给list
        list = list.stream().map((item) -> {
            Dish_菜品 dish = dishService.getOne(
                    Wrappers.<Dish_菜品>lambdaQuery()
                            .eq(Dish_菜品::getId, item.getDishId())
            );
            item.setImage(dish.getImage());
            return item;
        }).collect(Collectors.toList());

        //4、把整合好的List集合复制给套餐
        setmeal.setSetmealDishes(list);

        return R.success(setmeal);
    }
}
